package gui;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 * Tests if the user is logged in (is authorized) to access main.xhtml
 * 
 * @author Aleksander Zotov
 * 
 */
public class LoginCheck implements PhaseListener {

	private static final long serialVersionUID = 1L;

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

	public void beforePhase(PhaseEvent event) {
	}

	public void afterPhase(PhaseEvent event) {
		FacesContext fc = event.getFacesContext();

		// Check to see if they are on the login page.
		boolean loginPage = fc.getViewRoot().getViewId().lastIndexOf("login") > -1 ? true
				: false;
		if (!loginPage && !LoginBean.isLoggedIn()) {
			NavigationHandler nh = fc.getApplication().getNavigationHandler();
			nh.handleNavigation(fc, null, "logout");
		}
	}
}